package com.yan.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * TODO
 *
 * @Author: 汪焰
 * @Date: 2021/7/5 23:32
 */
@Configuration
@EnableRabbit
@ComponentScan("com.yan")
public class RabbitConfig {

    /*-----------深坑： 使用的交换器类型 一定是安装插件的交换器 x-delayed-message ----------------------*/

    //Queue
    @Bean
    public Queue queue() {
        return new Queue("queue.yan.delayed", true, false, false, null);
    }

    //Exchange
    @Bean
    public Exchange exchange() {
        Map<String, Object> arguments = new HashMap<>();
        //使用 指定类型交换器
        arguments.put("x-delayed-type", ExchangeTypes.DIRECT);
        // 使用 x-delayed-message 表示使用 delayed exchange 插件处理消息
        return new CustomExchange("exchange.yan.delayed", "x-delayed-message", true, false, arguments);
    }

    //Binding
    @Bean
    public Binding binding() {
        //创建一个绑定，不知道绑定的参数
        return BindingBuilder.bind(queue()).to(exchange()).with("key.yan.delayed").noargs();
    }

    @Bean
    @Autowired
    public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
        return new RabbitAdmin(factory);
    }

    @Bean
    @Autowired
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
        return new RabbitTemplate(factory);
    }

    @Bean
    @Autowired
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        //设置消息手动确认
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

}
